package com.study.basetype.util;

import okhttp3.*;
import okio.BufferedSink;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author flwu
 * @date 2020/3/21 11:46 PM
 * @MOTTO 保持空杯和敬畏
 */
//对照官方文档写是最靠谱的https://square.github.io/okhttp/recipes/   因为软件的不同版本可能有不同的微调
@Component
public class OkHttpUtil {

    private static final Logger log = LoggerFactory.getLogger(OkHttpUtil.class);

    private static OkHttpClient okHttpClient;

    private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain;charset=UTF-8");

    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

    private static final MediaType MEDIA_TYPE_XML = MediaType.parse("application/xml; charset=utf-8");

    private static final MediaType MEDIA_TYPE_FORM = MediaType.parse("appliction/x-www-form-urlencoded");


    /**
     * 默认header参数，如果传了自定义header会覆盖默认的
     */
    private static final Map<String, String> defaultHeader = new HashMap<String, String>() {
        {
            put("Accept-Encoding", "gzip, deflate");
            put("Connection", "keep-alive");
            put("Accept", "*/*");
        }
    };

    @Autowired
    public OkHttpUtil(OkHttpClient okHttpClient) {
        OkHttpUtil.okHttpClient  = okHttpClient;
    }

    public static String httpGet(String url) {
        return httpGet(url, null, null);
    }

    public static String httpGet(String url, Map<String, String> params) {
        return httpGet(url, params, null);
    }

    /**
     * 处理get请求
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static String httpGet(String url, Map<String, String> params, Map<String, String> headers) {
        String responseBody = "";
        //处理参数
        if (params != null && params.keySet().size() > 0) {
            boolean firstFlag = true;
            Iterator iterator = params.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    url += "?" + entry.getKey() + "=" + entry.getValue();
                    firstFlag = false;
                } else {
                    url += "&" + entry.getKey() + "=" + entry.getValue();
                }
            }
        }

        Headers endHeader = Headers.of(getHeaders(headers));
        Request request = new Request.Builder().url(url).headers(endHeader).build();

        //执行(可以到官网上了解下异步执行，如果需要的话，可以搞进来)
        return doExec(request);
    }

    public static String httpPost(String url, String params, MediaType mediaType) {
        return httpPost(url, params, null, mediaType);
    }

    /**
     * 处理post请求，参数为字符串 或 json
     * @param url
     * @param params
     * @param headers
     * @param mediaType
     * @return
     */
    public static String httpPost(String url, String params, Map<String, String> headers, MediaType mediaType) {
        String responseBody = "";
        Headers endHeader = Headers.of(getHeaders(headers));
        RequestBody requestBody = RequestBody.create(params, mediaType);
        Request request = new Request.Builder().url(url).post(requestBody).headers(endHeader).build();
        //执行
        return doExec(request);
    }

    public static String httpPost(String url, Map<String, String> params) {
        return httpPost(url, params, null);
    }

    /**
     * 处理post请求，参数为文本 或 stream 或 parameters
     * @param url
     * @param params
     * @param headers
     * @return
     */
    public static String httpPost(String url, Map<String, String> params, Map<String, String> headers) {
        String responseBody = "";

        //其实也可以用上面的方式(此处只为尝试新玩法)
        String strParams = "";
        for(Map.Entry<String, String> entry : params.entrySet()) {
            strParams += entry.getKey() + "=" + entry.getValue();
        }
        RequestBody requestBody = RequestBody.create(strParams, MEDIA_TYPE_FORM);
        //拿去头部
        Headers endHeader = Headers.of(getHeaders(headers));

        //执行请求
        Request request = new Request.Builder().url(url).post(requestBody).headers(endHeader).build();

        return doExec(request);
    }

    /**
     * 同步执行
     * @param request
     * @return
     */
    private static String doExec(Request request) {
        String responseBody = "";
        //执行
        try {
            //同步执行
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                responseBody = response.body().string();
            }
        } catch(Exception e) {
            log.error(e.getMessage());
        }
        return responseBody;
    }

    /**
     * 合并用户和默认的头部信息
     * @param headers
     * @return
     */
    private static Map<String, String> getHeaders(Map<String, String> headers) {
        //处理头部参数
        Map<String, String> endMapHeaders = new HashMap<String, String>();
        if (headers != null && headers.keySet().size() > 0) {
            for (Map.Entry<String,String> entry : defaultHeader.entrySet()) {
                endMapHeaders.put(entry.getKey(), entry.getValue());
            }
            for (Map.Entry<String,String> entry : headers.entrySet()) {
                endMapHeaders.put(entry.getKey(), entry.getValue());
            }
            Headers header1 = Headers.of(endMapHeaders);
        } else {
            endMapHeaders = defaultHeader;
        }
        return endMapHeaders;
    }

}
